#!/usr/bin/env bash
__Author__="liy"

source ./functions.sh
export CERT_DIR="${ROOT_DIR}/${1:-"etcd"}"

function init_env(){
    mkdir -pv $CERT_DIR
}


function create_ca(){
    openssl genrsa -out $CERT_DIR/ca.key 2048
    openssl req -config openssl.conf \
            -new -x509 -days 3651 -sha256 \
            -key $CERT_DIR/ca.key -extensions v3_ca \
            -out $CERT_DIR/ca.crt -subj "/CN=etcd-ca"
    
    touch $CERT_DIR/{index,index.txt}
    echo 1000 > $CERT_DIR/serial
    echo "unique_subject = no" > $CERT_DIR/index.txt.attr
}


function sign(){
    # Peer
    openssl_req $CERT_DIR peer "/CN=etcd"
    openssl_sign $CERT_DIR/ca.crt $CERT_DIR/ca.key $CERT_DIR peer etcd_peer_cert

    # Server
    openssl_req $CERT_DIR server "/CN=etcd"
    openssl_sign $CERT_DIR/ca.crt $CERT_DIR/ca.key $CERT_DIR server etcd_server_cert

    # APIServerClient
    openssl_req $CERT_DIR apiserver-etcd-client "/CN=etcd"
    openssl_sign $CERT_DIR/ca.crt $CERT_DIR/ca.key $CERT_DIR apiserver-etcd-client client_cert

    # Client
    openssl_req $CERT_DIR client "/CN=etcd"
    openssl_sign $CERT_DIR/ca.crt $CERT_DIR/ca.key $CERT_DIR client client_cert
}


function main(){
    init_env
    create_ca
    sign
    clean
}


main

